package com.sakiko.audiobook.account.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sakiko.audiobook.account.mapper.UserAccountMapper;
import com.sakiko.audiobook.account.service.UserAccountService;
import com.sakiko.audiobook.model.account.AccountDeductVo;
import com.sakiko.audiobook.model.account.UserAccount;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    @Autowired
    private UserAccountMapper userAccountMapper;

    /**
     * 初始化账户金额
     *
     * @param userId
     */
    @Override
    public void initAccount(Long userId) {
        // 创建 userAccount对象
        UserAccount userAccount = new UserAccount();
        // 赋值
        userAccount.setUserId(userId);
        userAccount.setTotalAmount(new BigDecimal("100"));
        userAccount.setAvailableAmount(new BigDecimal("100"));
        // 保存数据
        userAccountMapper.insert(userAccount);
    }

    @Override
    public BigDecimal getAvailableAmount(Long userId) {
        // 获取账户可用金额
        return userAccountMapper.selectOne(new LambdaQueryWrapper<UserAccount>().eq(UserAccount::getUserId, userId)).getAvailableAmount();
    }

    @Override
    public Boolean checkAndDeduct(AccountDeductVo accountDeductVo) {
        // 检查扣减金额是否成功
        try {
            int reflectRows = userAccountMapper.checkAndDeduct(accountDeductVo.getUserId(), accountDeductVo.getAmount());
            return reflectRows > 0;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
